import React from 'react'
import {withRouter,} from 'react-router-dom'
import {connect,} from 'react-redux'
import {Modal} from "antd-mobile";

// component
import GameRoomHeader from "./components/Header/Header"
import GameRoomTabs from "./components/Main/Main"
import {formatDate,} from "../../utils/dateService";
import {GlobalStore} from "../../context";
import {fetchLineUpReq} from "../../apis/nanoApi";
import LocalStorageService from "../../utils/LocalStorageService";
import constants, {app_name,} from "../../utils/constants";
import withDownload from "../../high-order-component/withDownload/withDownload";
import VideoHint from "./components/Header/VideoPlayer/video_hint";


class GameRoomContainer extends React.Component {

    static contextType = GlobalStore

    constructor(props) {
        super(props)
        this.storage = LocalStorageService
        this.matchId = this.props.match.params.gameId

        this.state = {
            atTop: true,
            onScrollEvent: true,
            containers: {},
            downloadShow: true,
            vodLive: false,
            liveLink: '',
        }
    }

    componentDidMount() {

        const match = this.props.match
        const location = this.props.location
        const matchId = match.params.gameId
        const search = location.search
        const login = LocalStorageService.get('isLogin')

        this.fetchLineUp(matchId)

        this.fetchUserDetail()
            .then((resp) => {
                return resp
            })
            .then((user) => {
                if (user) {
                    return this.fetchGameDetail(matchId)
                }
            })
            .then(() => {
                const game = this.props.currentGame
                const {statusid} = game.info
                if (!game.err && statusid < 8) {
                    this.freshGameDetail(matchId)
                }
            })
            .then(() => {
                const currentGame = this.props.game.currentGame
                const {
                    home_team,
                    away_team,
                } = currentGame
                const homeName = home_team.name_zh
                const awayName = away_team.name_zh
                document.title = homeName + ' VS ' + awayName
            })
            .then(() => {
                if (login) {
                    this.checkSearch({search, matchId,})
                }
            })

    }

    componentWillUnmount() {
        document.title = app_name
        this.props.setInitCurrentGame()
        this.clearFreshGameDetail()
    }

    hidden = () => {
        this.context.downloadApp.hidden()
        this.setState({
            downloadShow: false,
        })
    }

    fetchUserDetail = () => {
        const login = LocalStorageService.get('isLogin')
        const uid = localStorage.getItem('userid')
        const flag = this.props.user.userdetail.initFlag
        if (login && flag === 0) {
            return this.props.fetchUserDetail({uid,})
        } else {
            return new Promise((resolve => resolve(true)))
        }
    }


    checkSearch = ({search, matchId,}) => {

        if (search === '') return
        let obj = {}
        search
            .slice(1)
            .split('&')
            .map(kv => {
                const arr = kv.split('=')
                const key = arr[0]
                const val = arr[1]
                obj[key] = val
            })

        let {
            wechat,
            style,
            type,
            dealno,
        } = obj


        style = Number(style)

        let checkParams

        if (style <= 6 && style >= 1) {
            checkParams = {style, dealno,}
        }

        if (style === 100) {
            return
            // checkParams = {style, dealno,}
        }

        if (style === 101) {
            const game = this.props.currentGame
            // const home
            const home = game.home_team.name_zh
            const away = game.away_team.name_zh
            const dateObj = new Date(game.info.matchtime * 1000)
            const date = formatDate(dateObj, '-')
            const time = dateObj.toTimeString().split(' ')[0]
            const mark = `${home} VS ${away} ${date} ${time}`
            checkParams = {
                dealno,
                style,
                matchid: this.matchId,
                aitype: Number(type),
                wxdealno: '',
                mark,
            }
        }


        // xxxx vs xxxx  2006-01-02 15:04:05  让球/胜负平/大小球 ai预测，谢谢购买

        if (wechat && JSON.parse(wechat)) {
            const btnList = [
                { text: <span style={{color: constants.themeColor}}>已完成支付</span>, onPress: () => this.confirmWechatOrder(checkParams)},
                { text: <span style={{color: 'rgba(51,51,51,0.3)'}}>支付遇到问题, 重新支付</span>, onPress: () => {} },
                // {}
            ]
            Modal.alert('请确认微信支付是否完成', '', btnList)
        }
    }

    confirmWechatOrder = (params) => {
        this.props.doCheckWechatOrder(params)
    }

    fetchGameDetail = (id) => {
        return this.props.doFetchGameDetail({matchid: parseInt(id),})
    }

    freshGameDetail = (id) => {
        const freshInterval = 60000
        this.freshInterval = setInterval(() => {
            return this.fetchGameDetail(id)
        }, freshInterval)
    }

    fetchLineUp = (id) => {
        fetchLineUpReq({id: id,})
            .then((resp) => {
                if (resp.data.ok) {
                    const data = JSON.parse(resp.data.ok)
                }
            })
    }

    clearFreshGameDetail = () => {
        this.freshInterval && clearInterval(this.freshInterval)
    }

    setScrollCtn = (ctn, key) => {
        this.setState({
            containers: {
                [key]: ctn,
            }
        })
    }

    setAtTop = (boolean) => {
        this.setState({
            atTop: boolean,
        })
    }

    cancelOnScroll = () => {
        this.setState({
            onScrollEvent: false,
        })
    }

    shouldOnScroll = () => {
        this.setState({
            onScrollEvent: true,
        })
    }

    onInputTouched = () => {
        this.setState({
            touched: true,
        })
    }

    onInputBlur = () => {
        this.setState({
            touched: false,
        })
    }

    render() {
        const download = this.props.downloadShow
        return (
            <React.Fragment>
                {this.props.renderDownloadHint({level: 2,})}
                <GameRoomHeader
                    game={this.props.currentGame}
                    history={this.props.history}
                    atTop={this.state.atTop}
                    vodLive={this.state.vodLive}
                    liveLink={this.state.liveLink}
                    downloadShow={download}
                    onScrollEvent={this.state.onScrollEvent}
                    shouldOnScroll={this.shouldOnScroll}
                    cancelOnScroll={this.cancelOnScroll}
                />
                <GameRoomTabs
                    cancelOnScroll={this.cancelOnScroll}
                    onScrollEvent={this.state.onScrollEvent}
                    atTop={this.state.atTop}
                    setAtTop={this.setAtTop}
                    downloadShow={download}
                />
            </React.Fragment>
        )
    }
}

const mapState = state => ({
    user: state.user,
    game: state.game,
    games: state.game.games,
    currentGame: state.game.currentGame,
})

const mapDispatch = dispatch => ({
    fetchUserDetail:(payload) => dispatch.user.fetchUserDetail(payload),
    doFetchGameAi: (payload) => dispatch.game.doFetchGameAi(payload),
    doWechatPay: (payload) => dispatch.user.doWechatPay(payload),
    doCheckWechatOrder: (payload) => dispatch.user.doCheckWechatOrder(payload),
    doFetchGameDetail: (payload) => dispatch.game.doFetchGameDetail(payload),
    setInitCurrentGame: () => dispatch.game.setInitCurrentGame(),
    fetchGameAnalysis: (payload) => dispatch.game.doFetchGameAnalysis(payload),
    doFetchGamesOddsList: (payload) => dispatch.game.doFetchGamesOddsList(payload),
    doFetchOddsEuroLive: (payload) => dispatch.game.doFetchOddsEuroLive(payload),
    doFetchOddsListAll: (payload) => dispatch.game.doFetchOddsListAll(payload),
    doFetchGameEuroOddsList: (payload) => dispatch.game.doFetchGameEuroOddsList(payload),
})

export default connect(mapState, mapDispatch)(withRouter(withDownload(GameRoomContainer)))


// import React, {useEffect} from 'react'
// import {withRouter,} from 'react-router-dom'
// import {connect,} from 'react-redux'
//
//
// // components
// import GameRoomHeader from "./components/Header/Header"
// import GameRoomTabs from "./components/Main/Main"
//
// const GameRoomContainer = props => {
//
//     const gameId = props.match.params.gameId
//     const game = props.currentGame
//
//     useEffect(() => {
//         const matchId = gameId
//         props.doFetchGameDetail({matchId,})
//     }, [])
//
//
//     return (
//         <>
//             <GameRoomHeader
//                 game={game}
//                 history={props.history}
//             />
//             <GameRoomTabs/>
//         </>
//     )
// }
//
// const mapState = state => ({
//     currentGame: state.game.currentGame,
// })
//
// const mapDispatch = dispatch => ({
//     doFetchGameDetail: (payload) => dispatch.game.doFetchGameDetail(payload),
// })
//
// export default connect(mapState, mapDispatch)(withRouter(GameRoomContainer))

